package com.edgclub.edg.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.edgclub.edg.Constant;
import com.edgclub.edg.GuZhiApplication;
import com.edgclub.edg.R;
import com.edgclub.edg.activity.ChatSettingActivity;
import com.edgclub.edg.activity.GzMainActivity;
import com.edgclub.edg.activity.GzWebViewActivity;
import com.edgclub.edg.activity.MultiImageSelectorActivity;
import com.edgclub.edg.activity.UserInfoOtherActivity;
import com.edgclub.edg.api.FriendApi;
import com.edgclub.edg.api.param.MessageParam;
import com.edgclub.edg.api.param.UserParam;
import com.edgclub.edg.event.BroadCastEvent;
import com.edgclub.edg.event.EventBus;
import com.edgclub.edg.http.VolleyListener;
import com.edgclub.edg.huanxin.DemoHelper;
import com.edgclub.edg.huanxin.activity.ContextMenuActivity;
import com.edgclub.edg.huanxin.activity.ImageGridActivity;
import com.edgclub.edg.huanxin.domain.RobotUser;
import com.edgclub.edg.model.User;
import com.edgclub.edg.model.result.RunData;
import com.edgclub.edg.utils.util.JsonUtil;
import com.edgclub.edg.utils.util.UserPrefUtils;
import com.google.gson.Gson;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.dao.DaoHelper;
import com.hyphenate.easeui.dao.UserBeanDao;
import com.hyphenate.easeui.model.ChatBean;
import com.hyphenate.easeui.model.GroupChatBean;
import com.hyphenate.easeui.model.UserAuth;
import com.hyphenate.easeui.model.UserAuth2;
import com.hyphenate.easeui.model.UserBean;
import com.hyphenate.easeui.ui.EaseChatFragment;
import com.hyphenate.easeui.ui.EaseChatFragment.EaseChatFragmentListener;
import com.hyphenate.easeui.widget.EaseChatPrimaryMenu;
import com.hyphenate.easeui.widget.chatrow.EaseChatRow;
import com.hyphenate.easeui.widget.chatrow.EaseChatRowBigExpression;
import com.hyphenate.easeui.widget.chatrow.EaseChatRowFile;
import com.hyphenate.easeui.widget.chatrow.EaseChatRowImage;
import com.hyphenate.easeui.widget.chatrow.EaseChatRowLocation;
import com.hyphenate.easeui.widget.chatrow.EaseChatRowText;
import com.hyphenate.easeui.widget.chatrow.EaseChatRowVideo;
import com.hyphenate.easeui.widget.chatrow.EaseChatRowVoice;
import com.hyphenate.easeui.widget.chatrow.EaseCustomChatRowProvider;
import com.hyphenate.util.EasyUtils;
import com.hyphenate.util.PathUtil;
import com.rockerhieu.emojicon.EmojiconGridFragment;
import com.rockerhieu.emojicon.EmojiconsFragment;
import com.rockerhieu.emojicon.emoji.Emojicon;
import com.rockerhieu.emojicon.emoji.SerializeManager;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ChatFragment extends EaseChatFragment implements EaseChatFragmentListener, EmojiconGridFragment.OnEmojiconClickedListener,
        EmojiconsFragment.OnEmojiconBackspaceClickedListener {

    //避免和基类定义的常量可能发生的冲突，常量从11开始定义
    private static final int ITEM_VIDEO = 11;
    private static final int ITEM_FILE = 12;
    private static final int ITEM_VOICE_CALL = 13;
    private static final int ITEM_VIDEO_CALL = 14;

    private static final int REQUEST_CODE_SELECT_VIDEO = 11;
    private static final int REQUEST_CODE_SELECT_FILE = 12;
    private static final int REQUEST_CODE_GROUP_DETAIL = 13;
    private static final int REQUEST_CODE_CONTEXT_MENU = 14;

    private static final int MESSAGE_TYPE_SENT_VOICE_CALL = 1;
    private static final int MESSAGE_TYPE_RECV_VOICE_CALL = 2;
    private static final int MESSAGE_TYPE_SENT_VIDEO_CALL = 3;
    private static final int MESSAGE_TYPE_RECV_VIDEO_CALL = 4;


    private static final int REQUSET = 1000;
    HashMap<String, String> map;

    @Override
    public void onEmojiconClicked(Emojicon emojicon) {
        EmojiconsFragment.input(inputMenu.getPrimaryMenu1().getEmoji_editText(), emojicon);
    }

    @Override
    public void onEmojiconBackspaceClicked(View v) {
        EmojiconsFragment.backspace(inputMenu.getPrimaryMenu1().getEmoji_editText());
    }

    /**
     * 是否为环信小助手
     */
    private boolean isRobot;
    private UserPrefUtils mUserPrefUtils;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setUrlIntent(new Intent(getActivity(), GzWebViewActivity.class));
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    protected void setUpView() {
        EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                ThreadEnforcer.MAIN).register(this);
        map = (HashMap<String, String>) SerializeManager.loadFile(Constant.DIR + GuZhiApplication.getInstance().getUserId());

        setChatFragmentListener(this);
        if (chatType == Constant.CHATTYPE_SINGLE) {
            Map<String, RobotUser> robotMap = DemoHelper.getInstance().getRobotList();
            if (robotMap != null && robotMap.containsKey(toChatUsername)) {
                isRobot = true;
            }
        }
        super.setUpView();
        mUserPrefUtils = new UserPrefUtils(getActivity());
        // 设置标题栏点击事件
        titleBar.setLeftLayoutClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (EasyUtils.isSingleActivity(getActivity())) {
                    Intent intent = new Intent(getActivity(), GzMainActivity.class);
                    startActivity(intent);
                }
                sethistory();

            }
        });


        titleBar.setRightLayoutClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), ChatSettingActivity.class);
                intent.putExtra("chatBean", chatBean);
//                intent.putExtra("toChatUsername",toChatUsername);
//                intent.putExtra("chatType",chatType);
                startActivityForResult(intent, REQUSET);
            }
        });
        if (null == map)
            map = new HashMap<String, String>();
        else {
            ((EaseChatPrimaryMenu) inputMenu.chatPrimaryMenu).Emoji_editText.setText(map.get(chatBean.getImid()));
        }
        getChildFragmentManager()
                .beginTransaction()
                .add(R.id.emojicon_menu_container,
                        EmojiconsFragment.newInstance(false))
                .commit();
//        ((EaseEmojiconMenu)inputMenu.getEmojiconMenu()).addEmojiconGroup(EmojiconExampleGroupData.getData());
    }

    public void sethistory() {
        String key = chatBean.getImid();
        if (null == map)
            map = new HashMap<String, String>();
        if (!"".equals(((EaseChatPrimaryMenu) inputMenu.chatPrimaryMenu).Emoji_editText.getText() + "")) {
            map.put(key, ((EaseChatPrimaryMenu) inputMenu.chatPrimaryMenu).Emoji_editText.getText() + "");
        } else {
            map.remove(key);
        }
        SerializeManager.saveFile(map, Constant.DIR + GuZhiApplication.getInstance().getUserId());
        getActivity().finish();
    }

    @Override
    protected void registerExtendMenuItem() {
        //demo这里不覆盖基类已经注册的item,item点击listener沿用基类的
        super.registerExtendMenuItem();
        //增加扩展item
//        inputMenu.registerExtendMenuItem(R.string.attach_video, R.drawable.em_chat_video_selector, ITEM_VIDEO, extendMenuItemClickListener);
//        inputMenu.registerExtendMenuItem(R.string.attach_file, R.drawable.em_chat_file_selector, ITEM_FILE, extendMenuItemClickListener);
//        if(chatType == Constant.CHATTYPE_SINGLE){
//            inputMenu.registerExtendMenuItem(R.string.attach_voice_call, R.drawable.em_chat_voice_call_selector, ITEM_VOICE_CALL, extendMenuItemClickListener);
//            inputMenu.registerExtendMenuItem(R.string.attach_video_call, R.drawable.em_chat_video_call_selector, ITEM_VIDEO_CALL, extendMenuItemClickListener);
//        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CONTEXT_MENU) {
            switch (resultCode) {
                case ContextMenuActivity.RESULT_CODE_COPY: // 复制消息
                    clipboard.setText(((EMTextMessageBody) contextMenuMessage.getBody()).getMessage());
                    break;
                case ContextMenuActivity.RESULT_CODE_DELETE: // 删除消息
                    conversation.removeMessage(contextMenuMessage.getMsgId());
                    messageList.refresh();
                    break;

                case ContextMenuActivity.RESULT_CODE_FORWARD: // 转发消息
//                Intent intent = new Intent(getActivity(), ForwardMessageActivity.class);
//                intent.putExtra("forward_msg_id", contextMenuMessage.getMsgId());
//                startActivity(intent);

                    break;
                case ContextMenuActivity.RESULT_CODE_QUITGROUP: // 踢出群组
                    quitGroup();
                    break;
                default:
                    break;
            }
        }
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_SELECT_VIDEO: //发送选中的视频
                    if (data != null) {
                        int duration = data.getIntExtra("dur", 0);
                        String videoPath = data.getStringExtra("path");
                        File file = new File(PathUtil.getInstance().getImagePath(), "thvideo" + System.currentTimeMillis());
                        try {
                            try {
                                FileOutputStream fos = new FileOutputStream(file);
                                Bitmap ThumbBitmap = ThumbnailUtils.createVideoThumbnail(videoPath, 3);
                                ThumbBitmap.compress(CompressFormat.JPEG, 100, fos);
                                fos.close();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            sendVideoMessage(videoPath, file.getAbsolutePath(), duration);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                case REQUEST_CODE_SELECT_FILE: //发送选中的文件
                    if (data != null) {
                        Uri uri = data.getData();
                        if (uri != null) {
                            sendFileByUri(uri);
                        }
                    }
                    break;
                case REQUSET:
                    messageList.refresh();
                    break;
                case Constant.IMAGE_RESULT:
                    String userPath = data.getStringExtra("userPath") + "";
                    Uri selectedImage = Uri.parse(userPath);
                    if (selectedImage != null) {
                        sendPicByUri(selectedImage);
                    }
                    break;
                default:
                    break;
            }
        }

    }

    @Override
    public void onSetMessageAttributes(EMMessage message) {
//        if(isRobot){
        //设置消息扩展属性
        Map<String, Object> mess_ext = new HashMap<>();
        Map<String, String> mess_ext2 = new HashMap<>();
        Map<String, Map<String, String>> mess_ext3 = new HashMap<>();
        Map<String, String> mess_ext4 = new HashMap<>();
        User user = mUserPrefUtils.getUser();
        mess_ext.put("nick", user.getNick());
        mess_ext.put("imid", user.getImid());
        mess_ext.put("logo", user.getLogo());
        mess_ext.put("userid", user.getId());
        UserAuth userAuth = user.getUserAuth();
        if ("-1".equals(userAuth.getType())) {
            mess_ext.put("userauth", null);
        }
        else{
            UserAuth2 userAuth2 = new UserAuth2();
            userAuth2.setUserId(userAuth.getUserId());
            userAuth2.setAuthentication(userAuth.getAuthentication());
            userAuth2.setType(Integer.valueOf(userAuth.getType()));
            mess_ext.put("userauth", userAuth2);
        }
        mess_ext2.put("trueName", user.getGzno());
        mess_ext2.put("userNickname", user.getNick());
        mess_ext3.put("visitor", mess_ext2);
        message.setAttribute("userinfo", JsonUtil.getJsonStr(mess_ext));
        message.setAttribute("weichat", JsonUtil.getJsonStr(mess_ext3));
        if(chatType == EaseConstant.CHATTYPE_GROUP){
            String content = "";
            switch (message.getType()) {
                case TXT:
                    EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
                    content = txtBody.getMessage();
                    break;
                case IMAGE:
                    content = "发来一张图片";
                    break;
                case VOICE:
                    content = "发来一段语音";
                    break;
                default:
                    break;
            }
            try{
                JSONObject extJson = new JSONObject();
                extJson.put("em_push_title", user.getNick() + "(" + chatBean.getNick() + ")" + ":" + content);
                message.setAttribute("em_apns_ext",extJson);
            } catch (JSONException e){
                e.printStackTrace();
            }
        }
        else {
            String content = "";
            switch (message.getType()) {
                case TXT:
                    EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
                    content = txtBody.getMessage();
                    break;
                case IMAGE:
                    content = "发来一张图片";
                    break;
                case VOICE:
                    content = "发来一段语音";
                    break;
                default:
                    break;
            }
            try{
                JSONObject extJson = new JSONObject();
                extJson.put("em_push_title", user.getNick() + ":" + content);
                message.setAttribute("em_apns_ext",extJson);
            } catch (JSONException e){
                e.printStackTrace();
            }
        }
//            message.setAttribute("em_robot_message", isRobot);
//        }
    }

    @Override
    public EaseCustomChatRowProvider onSetCustomChatRowProvider() {
        //设置自定义listview item提供者
        return new CustomChatRowProvider();
    }


    @Override
    public void onEnterToChatDetails() {
    }

    @Override
    public void onAvatarClick(ChatBean chatBean1) {
        //头像点击事件
        Intent intent = new Intent(getActivity(), UserInfoOtherActivity.class);
        User user = RunData.getUserBeanMode(chatBean1);
        intent.putExtra("user", user);
        intent.putExtra("chat", true);
        if (chatBean.getChatType() == 1) {
            intent.putExtra("one", true);
        }
        startActivity(intent);
    }

    @Override
    public boolean onMessageBubbleClick(EMMessage message) {
        //消息框点击事件，demo这里不做覆盖，如需覆盖，return true
        return false;
    }

    @Override
    public void onMessageBubbleLongClick(EMMessage message) {
        //消息框长按
        startActivityForResult((new Intent(getActivity(), ContextMenuActivity.class)).putExtra("message", message),
                REQUEST_CODE_CONTEXT_MENU);
    }

    @Override
    public boolean onExtendMenuItemClick(int itemId, View view) {
        switch (itemId) {
            case ITEM_VIDEO: //视频
                Intent intent = new Intent(getActivity(), ImageGridActivity.class);
                startActivityForResult(intent, REQUEST_CODE_SELECT_VIDEO);
                break;
            case ITEM_FILE: //一般文件
                //demo这里是通过系统api选择文件，实际app中最好是做成qq那种选择发送文件
                selectFileFromLocal();
                break;
            case ITEM_VOICE_CALL: //音频通话
                startVoiceCall();
                break;
            case ITEM_VIDEO_CALL: //视频通话
                startVideoCall();
                break;
            case ITEM_PICTURE:
                Intent intent2 = new Intent(getActivity(), MultiImageSelectorActivity.class);
                intent2.putExtra("selectType", 3);
                // 是否显示拍摄图片
                intent2.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
                // 最大可选择图片数量
                intent2.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
                // 选择模式
                intent2.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
//                startActivity(intent2);
                startActivityForResult(intent2, Constant.IMAGE_RESULT);
                break;
            default:
                break;
        }
        //不覆盖已有的点击事件
        return false;
    }

    /**
     * 选择文件
     */
    protected void selectFileFromLocal() {
        Intent intent = null;
        if (Build.VERSION.SDK_INT < 19) { //19以后这个api不可用，demo这里简单处理成图库选择图片
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);

        } else {
            intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, REQUEST_CODE_SELECT_FILE);
    }

    /**
     * 拨打语音电话
     */
    protected void startVoiceCall() {
        if (!EMClient.getInstance().isConnected()) {
            Toast.makeText(getActivity(), R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
        } else {
//            startActivity(new Intent(getActivity(), VoiceCallActivity.class).putExtra("username", toChatUsername)
//                    .putExtra("isComingCall", false));
            // voiceCallBtn.setEnabled(false);
            inputMenu.hideExtendMenuContainer();
        }
    }

    /**
     * 拨打视频电话
     */
    protected void startVideoCall() {
        if (!EMClient.getInstance().isConnected())
            Toast.makeText(getActivity(), R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
        else {
//            startActivity(new Intent(getActivity(), VideoCallActivity.class).putExtra("username", toChatUsername)
//                    .putExtra("isComingCall", false));
            // videoCallBtn.setEnabled(false);
            inputMenu.hideExtendMenuContainer();
        }
    }

    /**
     * chat row provider
     */
    private final class CustomChatRowProvider implements EaseCustomChatRowProvider {
        @Override
        public int getCustomChatRowTypeCount() {
            //音、视频通话发送、接收共4种
            return 4;
        }

        @Override
        public int getCustomChatRowType(EMMessage message) {
            if (message.getType() == EMMessage.Type.TXT) {
                //语音通话类型
                if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, false)) {
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VOICE_CALL : MESSAGE_TYPE_SENT_VOICE_CALL;
                } else if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VIDEO_CALL, false)) {
                    //视频通话
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VIDEO_CALL : MESSAGE_TYPE_SENT_VIDEO_CALL;
                }
            }
            return 0;
        }

        @Override
        public EaseChatRow getCustomChatRow(EMMessage message, int position, BaseAdapter adapter) {
            if (message.getType() == EMMessage.Type.TXT) {
                // 语音通话,  视频通话
//                if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, false) ||
//                    message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VIDEO_CALL, false)){
//                    return new ChatRowVoiceCall(getActivity(), message, position, adapter);
//                }
            }
            return null;
        }

    }

    @Subscribe
    public void refreshDisturb(HashMap<String, Object> map) {
        String event = (String) map.get("event");
        if (null != event && BroadCastEvent.CHATLIST_DISTURB.equals(event)) {
            List<String> disturbList = (List<String>) SerializeManager.loadFile(Constant.notDisturb + GuZhiApplication.getInstance().getUserId() + "");
            if (null == disturbList)
                disturbList = new ArrayList<>();
            setDisturbList(disturbList);

        } else if (null != event && BroadCastEvent.CHATTITLE_REFRESH.equals(event)) {
            String imid = (String) map.get("imid") + "";
            UserBean userBean = (UserBean) DaoHelper.getInstance(getActivity(), EaseConstant.DB_NAME_CHAT).getTypeId(UserBeanDao.Properties.Imid, imid);
            if (null != userBean) {
                if (!"".equals(userBean.getUsername()))
                    titleBar.setTitle(userBean.getUsername());
                else
                    titleBar.setTitle(userBean.getNick());
            }

        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == event.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            // TODO
            sethistory();
            getActivity().finish();
            return false;
        }
        return false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                ThreadEnforcer.MAIN).unregister(this);
    }

    private void quitGroup() {
        String str = null;
        try {
            Gson gson = new Gson();
            str = contextMenuMessage.getStringAttribute("userinfo");
            ChatBean chatBean2 = gson.fromJson(str, ChatBean.class);
            MessageParam params = new MessageParam();
            params.setFromUserId(new UserPrefUtils(getActivity()).getUser().getId());
            params.setToUserId(chatBean2.getId());
            params.setGroupid(chatBean.getGroupid());
            // 开始登陆操作
            new FriendApi(getActivity()).kickGroup(params, new VolleyListener() {
                @Override
                public void onStart(String tag) {
                    Toast.makeText(getActivity() , "正在处理" , Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onSuccess(String response, String tag) {
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(response);
                        String data =  jsonObject.optString("data");
                        Toast.makeText(getActivity() , data , Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFaile(VolleyError volleyError, String tag) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Subscribe
    public void refreshListView(HashMap<String, Object> map){
        String event = (String) map.get("event");
        if (null!=event&&BroadCastEvent.MESSAGELIST_REFRESH.equals(event)) {
            String imid = (String) map.get("groupimid");
            if (chatBean.getImid().equals(imid)){
                messageList.refresh();
            }

        }
    }
}
